/**
 * 网关条件计算器
 * 用于根据流程图数据和表单数据计算网关分支的条件是否满足
 */

export interface GatewayBranch {
  flowId: string
  flowName: string
  targetNodeId: string
  targetNodeName: string
  targetNodeType: string
  conditionExpression: string
  conditionMet: boolean
}

export interface GatewayCondition {
  gatewayId: string
  gatewayName: string
  gatewayType: string
  activeBranches: GatewayBranch[]
  totalBranches: number
}

/**
 * 计算网关条件数据的主函数
 * @param nodeStatusList 节点状态列表
 * @param graphData 流程图数据（包含连线表达式）
 * @param formData 表单数据
 * @returns 网关条件数据
 */
export function calculateGatewayConditions(
  nodeStatusList: any[],
  graphData: any,
  formData: any
): GatewayCondition[] {
  console.log('calculateGatewayConditions - 开始计算网关条件数据')
  console.log('calculateGatewayConditions - 输入参数:', {
    hasNodeStatusList: !!nodeStatusList && nodeStatusList.length > 0,
    hasGraphData: !!graphData,
    hasFormData: !!formData
  })

  if (!nodeStatusList || !graphData || !formData) {
    console.log('calculateGatewayConditions - 数据不足，返回空数组')
    return []
  }

  // 找到当前正在执行的节点和已完成的节点
  const runningNodes = nodeStatusList.filter(node => 
    node.status === 'RUNNING' || node.status === 'ACTIVE'
  )
  
  const completedNodes = nodeStatusList.filter(node => 
    node.status === 'COMPLETED' || node.status === 'FINISHED'
  )

  console.log('calculateGatewayConditions - 找到正在执行的节点:', runningNodes)
  console.log('calculateGatewayConditions - 找到已完成的节点:', completedNodes)

  // 如果没有正在执行的节点，检查是否有已完成的节点
  if (runningNodes.length === 0 && completedNodes.length === 0) {
    console.log('calculateGatewayConditions - 没有正在执行或已完成的节点')
    return []
  }

  console.log('calculateGatewayConditions - 找到正在执行的节点:', runningNodes)

  const gatewayConditions: GatewayCondition[] = []

  // 遍历流程图中的所有节点，找到网关节点
  graphData.nodes.forEach(node => {
    if (isGatewayNode(node)) {
      console.log(`calculateGatewayConditions - 处理网关节点: ${node.id}`)
      
      const gatewayCondition = processGatewayNode(node, graphData, formData, runningNodes, completedNodes)
      if (gatewayCondition) {
        gatewayConditions.push(gatewayCondition)
      }
    }
  })

  console.log('calculateGatewayConditions - 最终网关条件数据:', gatewayConditions)
  
  // 添加详细的调试信息
  gatewayConditions.forEach((condition, index) => {
    console.log(`calculateGatewayConditions - 网关条件 ${index + 1}:`, {
      gatewayId: condition.gatewayId,
      gatewayName: condition.gatewayName,
      activeBranches: condition.activeBranches.map(branch => ({
        targetNodeId: branch.targetNodeId,
        targetNodeName: branch.targetNodeName,
        conditionMet: branch.conditionMet,
        conditionExpression: branch.conditionExpression
      })),
      totalBranches: condition.totalBranches
    })
  })
  
  return gatewayConditions
}

/**
 * 判断节点是否为网关节点
 */
function isGatewayNode(node: any): boolean {
  return node.type === 'gateway' || 
         node.id.includes('gateway') || 
         node.nodeType === 'gateway'
}

/**
 * 处理单个网关节点
 */
function processGatewayNode(
  gatewayNode: any,
  graphData: any,
  formData: any,
  runningNodes: any[],
  completedNodes: any[]
): GatewayCondition | null {
  // 查找从该网关出发的所有连线
  const outgoingEdges = graphData.edges.filter((edge: any) => edge.source === gatewayNode.id)
  
  if (outgoingEdges.length === 0) {
    console.log(`processGatewayNode - 网关 ${gatewayNode.id} 没有出边`)
    return null
  }

  console.log(`processGatewayNode - 网关 ${gatewayNode.id} 有 ${outgoingEdges.length} 个出边`)

  const activeBranches: GatewayBranch[] = []

  // 处理每个出边（分支）
  outgoingEdges.forEach(edge => {
    const branch = processGatewayBranch(edge, graphData, formData, runningNodes, completedNodes)
    if (branch && branch.conditionMet) {
      activeBranches.push(branch)
    }
  })

  // 如果没有激活的分支，返回null
  if (activeBranches.length === 0) {
    console.log(`processGatewayNode - 网关 ${gatewayNode.id} 没有激活的分支`)
    return null
  }

  return {
    gatewayId: gatewayNode.id,
    gatewayName: gatewayNode.data?.label || gatewayNode.label || gatewayNode.id,
    gatewayType: gatewayNode.type || 'gateway',
    activeBranches: activeBranches,
    totalBranches: outgoingEdges.length
  }
}

/**
 * 处理单个网关分支
 */
function processGatewayBranch(
  edge: any,
  graphData: any,
  formData: any,
  runningNodes: any[],
  completedNodes: any[]
): GatewayBranch | null {
  const targetNode = graphData.nodes.find((n: any) => n.id === edge.target)
  if (!targetNode) {
    console.log(`processGatewayBranch - 未找到目标节点: ${edge.target}`)
    return null
  }

  // 从连线中提取条件表达式
  const conditionExpression = extractConditionExpression(edge)
  console.log(`processGatewayBranch - 分支 ${edge.id} 条件表达式: ${conditionExpression}`)

  // 检查目标节点是否已经完成或正在执行
  const targetNodeStatus = findNodeStatus(targetNode.id, runningNodes, completedNodes)
  console.log(`processGatewayBranch - 目标节点 ${targetNode.id} 状态:`, targetNodeStatus)

  // 首先尝试通过条件表达式判断分支是否应该激活
  let conditionMet = false
  
  if (conditionExpression && formData) {
    // 如果有条件表达式和表单数据，先计算条件
    conditionMet = evaluateCondition(conditionExpression, formData)
    console.log(`processGatewayBranch - 条件计算结果: ${conditionExpression} = ${conditionMet}`)
  }
  
  // 分支激活逻辑：只有条件满足的分支才被认为是激活的
  // 目标节点的执行状态不应该影响分支的激活状态
  if (conditionMet) {
    console.log(`processGatewayBranch - 分支 ${edge.id} 激活：条件满足`)
  } else {
    console.log(`processGatewayBranch - 分支 ${edge.id} 未激活：条件不满足`)
  }

  return {
    flowId: edge.id,
    flowName: edge.data?.label || edge.label || edge.id,
    targetNodeId: targetNode.id,
    targetNodeName: targetNode.data?.label || targetNode.label || targetNode.id,
    targetNodeType: targetNode.type || 'unknown',
    conditionExpression: conditionExpression,
    conditionMet: conditionMet
  }
}

/**
 * 从连线中提取条件表达式
 */
function extractConditionExpression(edge: any): string {
  // 优先级1：从edge.data.conditionExpression获取
  if (edge.data && edge.data.conditionExpression) {
    return edge.data.conditionExpression
  }

  // 优先级2：从edge.conditionExpression获取
  if (edge.conditionExpression) {
    return edge.conditionExpression
  }

  // 优先级3：从edge.label获取
  if (edge.label) {
    return edge.label
  }

  // 优先级4：从edge.data.label获取
  if (edge.data && edge.data.label) {
    return edge.data.label
  }

  console.log(`extractConditionExpression - 未找到条件表达式，边ID: ${edge.id}`)
  return ''
}

/**
 * 计算条件表达式是否满足
 */
function evaluateCondition(conditionExpression: string, formData: any): boolean {
  if (!conditionExpression || !formData) {
    return false
  }

  try {
    console.log(`evaluateCondition - 开始计算条件: ${conditionExpression}`)
    console.log(`evaluateCondition - 表单数据:`, formData)

    // 清理条件表达式
    let expression = conditionExpression.trim()
    
    // 移除${}包装
    if (expression.startsWith('${') && expression.endsWith('}')) {
      expression = expression.substring(2, expression.length - 1)
    }

    // 解析条件表达式
    const result = parseConditionExpression(expression, formData)
    console.log(`evaluateCondition - 条件计算结果: ${result}`)
    
    return result

  } catch (error) {
    console.error('evaluateCondition - 条件计算失败:', conditionExpression, error)
    return false
  }
}

/**
 * 解析条件表达式
 */
function parseConditionExpression(expression: string, formData: any): boolean {
  console.log(`parseConditionExpression - 开始解析表达式: ${expression}`)
  
  // 处理布尔值
  if (expression.toLowerCase() === 'true') return true
  if (expression.toLowerCase() === 'false') return false

  // 处理比较表达式
  const comparisonOperators = ['>=', '<=', '!=', '==', '>', '<', '=']
  for (const operator of comparisonOperators) {
    if (expression.includes(operator)) {
      console.log(`parseConditionExpression - 检测到比较操作符: ${operator}`)
      return parseComparisonExpression(expression, operator, formData)
    }
  }

  // 处理变量引用
  console.log(`parseConditionExpression - 作为变量引用处理`)
  return parseVariableExpression(expression, formData)
}

/**
 * 解析比较表达式
 */
function parseComparisonExpression(expression: string, operator: string, formData: any): boolean {
  console.log(`parseComparisonExpression - 开始解析比较表达式: ${expression}, 操作符: ${operator}`)
  
  const parts = expression.split(operator, 2)
  if (parts.length !== 2) {
    console.log(`parseComparisonExpression - 表达式分割失败，parts:`, parts)
    return false
  }

  const leftVar = parts[0].trim()
  const rightValue = parts[1].trim()
  
  console.log(`parseComparisonExpression - 左侧变量: ${leftVar}, 右侧值: ${rightValue}`)

  // 获取左侧变量的值
  const leftValue = getVariableValue(leftVar, formData)
  if (leftValue === null || leftValue === undefined) {
    console.log(`parseComparisonExpression - 未找到变量: ${leftVar}`)
    return false
  }
  
  console.log(`parseComparisonExpression - 左侧变量值: ${leftValue}, 类型: ${typeof leftValue}`)

  // 解析右侧值
  const rightVal = parseValue(rightValue, formData)
  console.log(`parseComparisonExpression - 右侧值: ${rightVal}, 类型: ${typeof rightVal}`)

  // 执行比较
  const result = compareValues(leftValue, rightVal, operator)
  console.log(`parseComparisonExpression - 比较结果: ${leftValue} ${operator} ${rightVal} = ${result}`)
  
  return result
}

/**
 * 解析变量表达式
 */
function parseVariableExpression(expression: string, formData: any): boolean {
  // 直接查找变量
  const value = getVariableValue(expression, formData)
  
  if (value === null || value === undefined) {
    console.log(`parseVariableExpression - 未找到变量: ${expression}`)
    return false
  }

  // 根据变量类型判断
  if (typeof value === 'boolean') return value
  if (typeof value === 'string') return value.trim() !== ''
  if (typeof value === 'number') return value !== 0
  
  return value != null
}

/**
 * 查找节点状态
 */
function findNodeStatus(nodeId: string, runningNodes: any[], completedNodes: any[]): any | null {
  // 先查找正在执行的节点
  let status = runningNodes.find(node => 
    node.taskDefinitionKey === nodeId ||
    node.nodeName === nodeId ||
    node.taskName === nodeId ||
    (node.taskDefinitionKey && nodeId.includes(node.taskDefinitionKey)) ||
    (node.taskDefinitionKey && node.taskDefinitionKey.includes(nodeId))
  )
  
  if (status) {
    return status
  }
  
  // 再查找已完成的节点
  status = completedNodes.find(node => 
    node.taskDefinitionKey === nodeId ||
    node.nodeName === nodeId ||
    node.taskName === nodeId ||
    (node.taskDefinitionKey && nodeId.includes(node.taskDefinitionKey)) ||
    (node.taskDefinitionKey && node.taskDefinitionKey.includes(nodeId))
  )
  
  return status || null
}

/**
 * 获取变量值
 */
function getVariableValue(variable: string, formData: any): any {
  console.log(`getVariableValue - 查找变量: ${variable}`)
  console.log(`getVariableValue - 表单数据:`, formData)
  console.log(`getVariableValue - 表单数据键:`, Object.keys(formData))

  // 支持嵌套属性访问，如 formData.amount
  if (variable.includes('.')) {
    const parts = variable.split('.')
    let current = formData
    
    for (const part of parts) {
      if (current && typeof current === 'object' && current.hasOwnProperty(part)) {
        current = current[part]
      } else {
        return null
      }
    }
    return current
  }

  // 优先级1：优先在 formData 对象内查找
  if (formData.formData && typeof formData.formData === 'object') {
    if (formData.formData.hasOwnProperty(variable)) {
      console.log(`getVariableValue - 在formData内找到变量: ${variable} = ${formData.formData[variable]}`)
      return formData.formData[variable]
    }
  }

  // 优先级2：直接查找变量
  if (formData.hasOwnProperty(variable)) {
    console.log(`getVariableValue - 直接找到变量: ${variable} = ${formData[variable]}`)
    return formData[variable]
  }

  // 优先级3：增强字段匹配：尝试查找包含该表达式的字段
  // 但排除一些常见的顶层字段，避免误匹配
  const excludeFields = ['name', 'formName', 'processName', 'id', 'status', 'createTime', 'updateTime']
  const matchingKeys = Object.keys(formData).filter(key => {
    // 排除顶层字段
    if (excludeFields.includes(key)) return false
    // 只匹配完全包含变量的字段
    return key.includes(variable)
  })
  
  if (matchingKeys.length > 0) {
    console.log(`getVariableValue - 找到匹配的字段: ${matchingKeys.join(', ')}`)
    // 使用第一个匹配的字段
    const value = formData[matchingKeys[0]]
    console.log(`getVariableValue - 使用匹配字段: ${matchingKeys[0]} = ${value}`)
    return value
  }

  console.log(`getVariableValue - 未找到变量: ${variable}`)
  return null
}

/**
 * 解析值
 */
function parseValue(value: string, formData: any): any {
  value = value.trim()

  // 移除引号
  if ((value.startsWith('"') && value.endsWith('"')) || 
      (value.startsWith("'") && value.endsWith("'"))) {
    return value.substring(1, value.length - 1)
  }

  // 尝试解析为数字
  if (!isNaN(Number(value))) {
    return value.includes('.') ? parseFloat(value) : parseInt(value)
  }

  // 作为变量处理
  return getVariableValue(value, formData)
}

/**
 * 比较值
 */
function compareValues(left: any, right: any, operator: string): boolean {
  try {
    console.log(`compareValues - 开始比较: ${left} ${operator} ${right}`)
    console.log(`compareValues - 左侧类型: ${typeof left}, 右侧类型: ${typeof right}`)
    
    // 数字比较
    if (typeof left === 'number' && typeof right === 'number') {
      const result = compareNumbers(left, right, operator)
      console.log(`compareValues - 数字比较结果: ${left} ${operator} ${right} = ${result}`)
      return result
    }

    // 字符串比较
    if (typeof left === 'string' && typeof right === 'string') {
      const result = compareStrings(left, right, operator)
      console.log(`compareValues - 字符串比较结果: ${left} ${operator} ${right} = ${result}`)
      return result
    }

    // 混合类型比较：尝试转换为相同类型
    if (typeof left === 'string' && typeof right === 'number') {
      // 左侧是字符串，右侧是数字，尝试将左侧转换为数字
      const leftNum = parseFloat(left)
      if (!isNaN(leftNum)) {
        const result = compareNumbers(leftNum, right, operator)
        console.log(`compareValues - 混合类型比较(字符串转数字): ${leftNum} ${operator} ${right} = ${result}`)
        return result
      }
    }
    
    if (typeof left === 'number' && typeof right === 'string') {
      // 左侧是数字，右侧是字符串，尝试将右侧转换为数字
      const rightNum = parseFloat(right)
      if (!isNaN(rightNum)) {
        const result = compareNumbers(left, rightNum, operator)
        console.log(`compareValues - 混合类型比较(数字转字符串): ${left} ${operator} ${rightNum} = ${result}`)
        return result
      }
    }

    // 其他情况，转换为字符串比较
    const leftStr = String(left)
    const rightStr = String(right)
    const result = compareStrings(leftStr, rightStr, operator)
    console.log(`compareValues - 字符串比较结果: ${leftStr} ${operator} ${rightStr} = ${result}`)
    
    return result

  } catch (error) {
    console.error('compareValues - 比较失败:', left, operator, right, error)
    return false
  }
}

/**
 * 比较数字
 */
function compareNumbers(left: number, right: number, operator: string): boolean {
  switch (operator) {
    case '>': return left > right
    case '>=': return left >= right
    case '<': return left < right
    case '<=': return left <= right
    case '==': return left === right
    case '!=': return left !== right
    case '=': return left === right
    default: return false
  }
}

/**
 * 比较字符串
 */
function compareStrings(left: string, right: string, operator: string): boolean {
  switch (operator) {
    case '==': return left === right
    case '!=': return left !== right
    case '=': return left === right
    default: return false
  }
}

/**
 * 获取网关条件数据的主函数（保持向后兼容）
 */
export function getGatewayConditions(
  nextNodes?: any[],
  formData?: any,
  nodeStatusList?: any[],
  graphData?: any
): GatewayCondition[] {
  console.log('getGatewayConditions - 开始获取网关条件数据')
  console.log('getGatewayConditions - 输入参数:', {
    hasNextNodes: !!nextNodes && nextNodes.length > 0,
    hasFormData: !!formData,
    hasNodeStatusList: !!nodeStatusList && nodeStatusList.length > 0,
    hasGraphData: !!graphData
  })

  // 使用新的计算方式
  if (nodeStatusList && nodeStatusList.length > 0 && graphData && formData) {
    console.log('getGatewayConditions - 使用新的计算方式')
    return calculateGatewayConditions(nodeStatusList, graphData, formData)
  }

  console.log('getGatewayConditions - 数据不足，返回空数组')
  return []
}

export default {
  calculateGatewayConditions,
  getGatewayConditions
}
